//
//  RCNetWorking.m
//  AFNetWorking
//
//  Created by Marx on 15/10/20.
//  Copyright © 2015年 任成. All rights reserved.
//

#import "RCNetWorking.h"
#import "AFNetworking.h"
@implementation RCNetWorking

#pragma mark - AFNetWorkingGET
+ (void)GETDataWithAFN:(NSString *)url cookie:(NSString *)cookie completion:(JSONBLOCK)block error:(ERRORBLOCK)errorblock
{
    //网络请求状态判断
//    [[self class] networkReachabilityStatus:^(id result) {
//        if ([result isEqualToNumber:@0]) {
//            //在向服务端发送请求状态栏显示网络活动标志：
//            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//        } else {
//            //在向服务端发送请求状态栏显示网络活动标志：
//            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
//        }
//    }];
    //中文字符转化
    //    NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    //初始化
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //返回数据的格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",nil]];
    if (cookie) {
        // 接口带Cookie
        // 参数1: Cookie值
        // 参数2: Cookie类型
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    //获取路径
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *pathString = path.lastObject;
    //拼接
    NSString *pathLast = [NSString stringWithFormat:@"/%lu.text", (unsigned long)[url hash]];
    //创建字符串文件储存路径
    NSString *PathName = [pathString stringByAppendingString:pathLast];
    
    
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        //如果请求成功,回调 请求到的数据,同时 做本地缓存
        block(responseObject);
        
        //请求结束状态栏隐藏网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        //归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:PathName];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败, 错误信息:%@", error);
        
        //在这里读取本地缓存
        if ([[NSFileManager defaultManager] fileExistsAtPath:PathName]) {
            //从本地读缓存文件(解档)
            id result = [NSKeyedUnarchiver unarchiveObjectWithFile:PathName];
            block(result);
        }
        // 用单例确保提示方法只执行一次
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"net2"] == NO) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"net2"];
            // 便利构造器初始化
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前网络不好" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *canelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                // 点击取消按钮执行的代码
            }];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // 点击确定按钮执行的代码
            }];
            // 给alert添加操作
            [alert addAction:canelAction];
            [alert addAction:okAction];
            // 模态显示
            //获取视图的根视图控制器 模态
            UIWindow *app = [UIApplication sharedApplication].keyWindow;
            [app.rootViewController presentViewController:alert animated:YES completion:nil];
        } else {
            
        }
        
    }];
}



#pragma mark - GET网络请求
+ (void)getUrl:(NSString *)urlStr cookie:(NSString *)cookie Result:(JSONBLOCK)block {
    
//    //网络请求状态判断
//    [[self class] networkReachabilityStatus:^(id result) {
//        if ([result isEqualToNumber:@0]) {
//            //在向服务端发送请求状态栏显示网络活动标志：
//            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//        } else {
//            //在向服务端发送请求状态栏显示网络活动标志：
//            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
//        }
//    }];
    NSString *urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //返回数据格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    
    if (cookie)
    {
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    
    [manager GET:urlString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        // 如果请求成功, 回调请求到得数据, 同时在这里做本地缓存
        block(responseObject);
        //请求结束状态栏隐藏网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        // 在这里读取本地缓存
    }];
}



+ (void)postUrl:(NSString *)url parame:(id)parame cookie:(NSString *)cookie bodyStr:(NSString *)bodyStr result:(JSONBLOCK)block
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //接口带Cookie
    if (cookie) {
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    
    //返回数据格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    
    if (cookie)
    {
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
        if ([cookie isEqualToString:@"duid=0"])
        {
            [manager.requestSerializer setValue:@"568"forHTTPHeaderField:@"version"];
            [manager.requestSerializer setValue:@"3" forHTTPHeaderField:@"client"];
        }
    }
    //如果请求成功 , 回调请求到的数据 , 同时 在这里 做本地缓存
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long)[bodyStr hash]];
    // 存储的沙盒路径
    NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    [manager POST:url parameters:parame success:^(NSURLSessionDataTask *task, id responseObject) {
        // 写入本地
        [responseObject writeToFile:[path_doc stringByAppendingPathComponent:path] atomically:YES];

        block(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //从本地取出
        id result = [NSDictionary dictionaryWithContentsOfFile:[path_doc stringByAppendingPathComponent:path]];

        block(result);
        
    }];
    
}

+ (NSDictionary *)dictionaryWithString:(NSString *)str
{
    // 前后加{""}
    NSString *str1 = [NSString stringWithFormat:@"{\"%@\"}", str];
    // =替换为":"
    NSString *str2 = [str1 stringByReplacingOccurrencesOfString:@"=" withString:@"\":\""];
    // &替换为","
    NSString *str3 = [str2 stringByReplacingOccurrencesOfString:@"&" withString:@"\",\""];
    NSData *data = [str3 dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return dic;
}

#pragma mark - 网络请求状态判断
+ (void)networkReachabilityStatus:(JSONBLOCK)block
{
    // 网络连接检测封装
    AFNetworkReachabilityManager *reachManeger = [AFNetworkReachabilityManager sharedManager];
    // 开始检测
    [reachManeger startMonitoring];
    
    [reachManeger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                block(@0);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                block(@1);
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                block(@2);
                break;
            case AFNetworkReachabilityStatusUnknown:
                block(@(-1));
                break;
            default:
                break;
        }
    }];
    
}

@end
